<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="profile-header">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/user/upload"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              name="file"
            >
              <el-avatar :size="100" :src="getAvatarUrl" class="avatar" />
              <div class="avatar-hover-mask">
                <el-icon><Camera /></el-icon>
                <span>点击更换头像</span>
              </div>
            </el-upload>
            <h2 class="username">管理员</h2>
            <p class="role">系统管理员</p>
          </div>
          <el-divider />
          <div class="profile-info">
            <p><el-icon><User /></el-icon> 账号：admin</p>
            <p><el-icon><Phone /></el-icon> 手机：138****8000</p>
            <p><el-icon><Message /></el-icon> 邮箱：admin@example.com</p>
            <p><el-icon><Location /></el-icon> 部门：运营部</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button type="primary" @click="handleEdit">编辑信息</el-button>
            </div>
          </template>
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            :disabled="!isEditing"
          >
            <el-form-item label="账号" prop="username">
              <el-input v-model="form.username" disabled />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" />
            </el-form-item>
            <el-form-item label="部门" prop="department">
              <el-select v-model="form.department" placeholder="请选择部门">
                <el-option label="运营部" value="运营部" />
                <el-option label="财务部" value="财务部" />
              </el-select>
            </el-form-item>
            <el-form-item label="职位" prop="position">
              <el-select v-model="form.position" placeholder="请选择职位">
                <el-option label="员工" value="员工" />
                <el-option label="经理" value="经理" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="isEditing">
              <el-button type="primary" @click="handleSave">保存</el-button>
              <el-button @click="handleCancel">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Phone, Message, Location, Camera } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'  // 导入用户状态管理

const userStore = useUserStore()
const isEditing = ref(false)
const formRef = ref(null)
const userInfo = reactive({
  image: '',
  username: '',
  name: '',
  phone: '',
  email: '',
  department: '',
  position: ''
})

// 获取带时间戳的头像URL
const getAvatarUrl = computed(() => {
  if (!userInfo.image) return ''
  // 添加时间戳参数来避免缓存
  const timestamp = new Date().getTime()
  return `${userInfo.image}?t=${timestamp}`
})

// 上传头像的请求头
const uploadHeaders = computed(() => ({
  'Token': localStorage.getItem('Token')
}))

// 处理头像上传成功
const handleAvatarSuccess = (response) => {
  if (response.code === 200 && response.data) {
    // 更新用户信息，包括头像
    fetchUserInfo()
    // 更新全局用户状态中的头像
    userStore.updateUserInfo({ image: response.data.image })
    ElMessage.success('头像上传成功')
    // 刷新页面以确保所有组件更新
    window.location.reload()
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

const form = reactive({
  username: '',
  name: '',
  phone: '',
  email: '',
  department: '',
  position: ''
})

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const token = localStorage.getItem('Token')
    const response = await fetch('http://localhost:8080/user', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })

    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    if (result.code === 200) {
      // 更新用户信息
      Object.assign(userInfo, {
        image: result.data.image || '',
        username: result.data.username || '',
        name: result.data.name || '',
        phone: result.data.phone || '',
        email: result.data.email || '',
        department: result.data.department || '',
        position: result.data.position || ''
      })
      
      // 更新全局用户状态
      userStore.updateUserInfo({
        image: result.data.image,
        username: result.data.username,
        name: result.data.name,
        phone: result.data.phone,
        email: result.data.email,
        department: result.data.department,
        position: result.data.position
      })
      
      // 更新表单数据
      Object.assign(form, {
        username: result.data.username || '',
        name: result.data.name || '',
        phone: result.data.phone || '',
        email: result.data.email || '',
        department: result.data.department || '',
        position: result.data.position || ''
      })
      
      // 更新头像上方的用户名和角色
      document.querySelector('.username').textContent = result.data.name
      document.querySelector('.role').textContent = result.data.position
      
      // 更新基本信息显示
      document.querySelector('.profile-info').innerHTML = `
        <p><el-icon><User /></el-icon> 账号：${result.data.username}</p>
        <p><el-icon><Phone /></el-icon> 手机：${result.data.phone}</p>
        <p><el-icon><Message /></el-icon> 邮箱：${result.data.email}</p>
        <p><el-icon><Location /></el-icon> 部门：${result.data.department}</p>
      `
    } else {
      throw new Error(result.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败：', error)
    ElMessage.error('获取用户信息失败：' + error.message)
  }
}

// 在组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})

const rules = {
  username: [
    { required: true, message: '账号不能为空', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入部门', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' }
  ]
}

const handleEdit = () => {
  isEditing.value = true
}

const handleSave = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const token = localStorage.getItem('Token')
        const response = await fetch('http://localhost:8080/user/update', {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Token': token
          },
          body: JSON.stringify({
            username: form.username,
            name: form.name,
            phone: form.phone,
            email: form.email,
            department: form.department,
            position: form.position,
            image: userInfo.image
          })
        })

        if (response.status === 401) {
          localStorage.removeItem('Token')
          localStorage.removeItem('user')
          window.location.href = '/login'
          return
        }

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const result = await response.json()
        if (result.code === 200) {
          ElMessage.success('保存成功')
          isEditing.value = false
          // 重新获取用户信息以更新显示
          fetchUserInfo()
        } else {
          throw new Error(result.message || '保存失败')
        }
      } catch (error) {
        console.error('保存失败：', error)
        ElMessage.error('保存失败：' + error.message)
      }
    }
  })
}

const handleCancel = () => {
  isEditing.value = false
  // 重新获取用户信息
  fetchUserInfo()
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  text-align: center;
}

.profile-header {
  padding: 20px 0;
}

.username {
  margin: 10px 0 5px;
  font-size: 20px;
  color: #303133;
}

.role {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.profile-info {
  text-align: left;
  padding: 0 20px;
}

.profile-info p {
  margin: 10px 0;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-uploader {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.avatar {
  display: block;
}

.avatar-hover-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-hover-mask:hover {
  opacity: 1;
}

.avatar-hover-mask .el-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.avatar-hover-mask span {
  font-size: 12px;
}
</style> 